package io.arukas.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;

/**
 * Created by IntelliJ IDEA. <br/>
 * Author: YuXian Niu <br/>
 * Email: niuyuxian@163.com <br/>
 * Create: 2021-08-15 21:20 <br/>
 */
@Controller
public class UserEndpoint {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @GetMapping(value = "user/login")
    public String userLogin(HttpServletRequest request, ModelMap modelMap) {
        final String ERROR = "error";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            logger.debug("authentication: {}", authentication);

            HttpSession session = request.getSession(false);
            if (session != null) {
                // 默认是放在session中.
                String key = WebAttributes.AUTHENTICATION_EXCEPTION;
                if (session.getAttribute(key) != null) {
                    AuthenticationException exception = (AuthenticationException) session.getAttribute(key);
                    modelMap.addAttribute(ERROR, exception.getMessage());
                    // 将错误信息放到request中后山删除session中的数据.
                    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
                }

            }
            return "user/user_login";
        }
        return "redirect:/user/page";
    }

    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    @GetMapping(value = "user/page")
    public String userPage(Principal principal) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        logger.info("username: {}", userDetails.getUsername());
        logger.info("password: {}", userDetails.getPassword());
        authentication.getAuthorities().forEach(perm -> logger.info("perm: {}", perm));
        userDetails.getAuthorities().forEach(perm -> logger.info("perm: {}", perm));
        return "user/user_page";
    }
}
